package com.fly.hbn.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fly.hbn.model.Country;
import com.fly.hbn.service.CountryService;

@Controller
public class CountryController
{
    @Autowired
    CountryService countryService;
    
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public String add(@ModelAttribute("country") Country country)
    {
        if (country.getId() == 0)
        {
            countryService.addCountry(country);
        }
        else
        {
            countryService.updateCountry(country);
        }
        return "redirect:/list";
    }
    
    @RequestMapping(value = "/delete/{id}", method = RequestMethod.GET)
    public String delete(@PathVariable("id") int id)
    {
        countryService.deleteCountry(id);
        return "redirect:/list";
    }
    
    @ResponseBody
    @RequestMapping(value = "/get/{id}", method = RequestMethod.GET)
    public Country get(@PathVariable int id)
    {
        return countryService.getCountry(id);
    }
    
    @RequestMapping(value = {"/", "/list"}, method = RequestMethod.GET)
    public String list(Model model)
    {
        List<Country> list = countryService.getAllCountries();
        model.addAttribute("item", new Country());
        model.addAttribute("list", list);
        return "show";
    }
    
    @RequestMapping(value = "/update/{id}", method = RequestMethod.GET)
    public String update(@PathVariable("id") int id, Model model)
    {
        model.addAttribute("item", countryService.getCountry(id));
        model.addAttribute("list", countryService.getAllCountries());
        return "show";
    }
}
